﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace Faz.SideWinderSC.Client
{
    /// <summary>
    /// Base window implementation that manages a reshaped window.
    /// </summary>
    [TemplatePart(Name="PART_TitleBar", Type=typeof(Thumb))]
    public class BaseWindow : Window
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseWindow"/> class.
        /// </summary>
        public BaseWindow()
        {
            this.CommandBindings.Add(new CommandBinding(Commands.WindowClose, this.OnWindowCloseExecuted));
            this.CommandBindings.Add(new CommandBinding(Commands.WindowChangeState, this.OnWindowChangeStateExecuted));
            this.Loaded += this.OnLoaded;
        }

        /// <summary>
        /// Gets the thumb associated with the capability to move the window.
        /// </summary>
        private Thumb TitleBar
        {
            get { return this.Template.FindName("PART_TitleBar", this) as Thumb;}
        }

        /// <summary>
        /// Called when the window is loaded.
        /// </summary>
        /// <param name="sender">The parameter is not used.</param>
        /// <param name="e">The parameter is not used.</param>
        protected virtual void OnLoaded(object sender, RoutedEventArgs e)
        {
            var titleBar = this.TitleBar;
            if (titleBar == null)
            {
                return;
            }

            titleBar.DragDelta += new DragDeltaEventHandler(this.OnMoveDragDelta);
        }

        /// <summary>
        /// Called when the title bar is dragged.
        /// </summary>
        /// <param name="sender">The parameter is not used.</param>
        /// <param name="e">The details of the event.</param>
        private void OnMoveDragDelta(object sender, DragDeltaEventArgs e)
        {
            this.Left += e.HorizontalChange;
            this.Top += e.VerticalChange;
        }

        /// <summary>
        /// Called when the "Window Close" command is executed.
        /// </summary>
        /// <param name="sender">The parameter is not used.</param>
        /// <param name="e">The parameter is not used.</param>
        private void OnWindowCloseExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Called when the "Window Change State" command is executed.
        /// </summary>
        /// <param name="sender">The parameter is not used.</param>
        /// <param name="e">The details of the event.</param>
        private void OnWindowChangeStateExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Parameter is WindowState)
            {
                WindowState state = (WindowState)e.Parameter;
                this.WindowState = state;
            }
        }
    }
}
